#!/usr/bin/env python3
"""调试 ChromaDB 搜索返回的数据结构"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.config import load_config
from src.database.chromadb_client import ChromaDBClient

async def debug_chromadb_search_structure():
    """调试 ChromaDB 搜索返回的数据结构"""
    print("=== 调试 ChromaDB 搜索返回的数据结构 ===")
    
    try:
        # 加载配置
        config = load_config()
        
        # 初始化 ChromaDBClient
        chromadb_client = ChromaDBClient(config)
        await chromadb_client.connect()
        
        print("✅ ChromaDBClient 连接成功")
        
        # 测试搜索
        query = "王者荣耀"
        user_id = "default_user"
        limit = 5
        
        print(f"\n搜索参数:")
        print(f"  query: {query}")
        print(f"  user_id: {user_id}")
        print(f"  limit: {limit}")
        
        # 调用 search_conversations 方法
        results = await chromadb_client.search_conversations(query, user_id, limit)
        
        print(f"\n搜索结果:")
        print(f"  结果数量: {len(results)}")
        print(f"  结果类型: {type(results)}")
        
        if results:
            print(f"\n详细结果:")
            for i, result in enumerate(results):
                print(f"  结果 [{i+1}]:")
                print(f"    类型: {type(result)}")
                print(f"    键: {list(result.keys()) if isinstance(result, dict) else 'N/A'}")
                print(f"    内容: {result}")
                
                # 检查是否有 conversation_id 字段
                if isinstance(result, dict):
                    conv_id = result.get('conversation_id')
                    print(f"    conversation_id: {conv_id}")
                    
                    # 检查其他可能的ID字段
                    for key in result.keys():
                        if 'id' in key.lower():
                            print(f"    {key}: {result[key]}")
                print()
        else:
            print("  ❌ 没有找到任何结果")
            
            # 尝试不带用户过滤的搜索
            print(f"\n尝试不带用户过滤的搜索...")
            results_no_filter = await chromadb_client.search_conversations(query, None, limit)
            print(f"  无过滤结果数量: {len(results_no_filter)}")
            
            if results_no_filter:
                print(f"  第一个结果: {results_no_filter[0]}")
        
        # 清理
        await chromadb_client.cleanup()
        print("\n✅ 调试完成")
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(debug_chromadb_search_structure())